<template>
  <div>
    <h2>购物车</h2>
    <ul v-if="cart.length">
      <li v-for="item in cart" :key="item.id">
        {{ item.name }} - ￥{{ item.price.toFixed(2) }} x {{ item.quantity }}
        <button @click="onRemove(item.id)">移除</button>
      </li>
    </ul>
    <p v-else>购物车空空如也</p>
    <button @click="goCheckout" :disabled="!cart.length">去结算</button>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { getCart, deleteCartItem } from '@/utils/cart'

const cart = ref([])
const router = useRouter()

async function fetchCart() {
  const res = await getCart()
  if (res.data.code === 0) cart.value = res.data.data
}

async function onRemove(id) {
  await deleteCartItem(id)
  fetchCart()
}

function goCheckout() {
  router.push('/checkout')
}

onMounted(fetchCart)
</script>
